package com.jflyfox.component.controller;

import java.io.File;

import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jflyfox.component.util.DateUtils;
import com.oreilly.servlet.multipart.FileRenamePolicy;

/**
 * 2016年11月20日 14:59:07
 * 
 * 文件重命名规则。参考：http://blog.dreamlu.net/blog/74
 * 
 * @author zempty
 *
 */
public class UpFileRenamePolicy implements FileRenamePolicy {

	@Override
	public File rename(File f) {
		String webRoot = PathKit.getWebRootPath();
		//获取用户在jfinal配置的上传路径
		String saveDir = JFinal.me().getConstants().getBaseUploadPath();
		
		StringBuffer newFilename = new StringBuffer(webRoot);
		newFilename.append(File.separator);
		newFilename.append(StrKit.isBlank(saveDir) ? "upload" : saveDir);
		newFilename.append(File.separator);
		newFilename.append(DateUtils.getByType("year"));
		newFilename.append(File.separator);
		newFilename.append(DateUtils.getByType("month"));
		newFilename.append(File.separator);
		newFilename.append(DateUtils.getByType("day"));
		newFilename.append(File.separator);
		newFilename.append(System.currentTimeMillis());
		newFilename.append(f.getName().substring(f.getName().lastIndexOf(".")));
		
		File dest = new File(newFilename.toString());
		File parent = dest.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
		
		return dest;
	}

}
